# coding:utf-8



from BeautifulReport import BeautifulReport
import unittest,time
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import os
from settings import log
from email.mime.multipart import MIMEMultipart
from case import maincase


def NewReport(test_report):
    lists = os.listdir(test_report)
    lists.sort(key=lambda fn: os.path.getatime(test_report + "/" + fn))
    file_new = os.path.join(test_report, lists[-1])
    return file_new


def SendMail(file,STMPServer,From,password,To):
    f = open(file,'rb')
    mailbody = f.read()
    f.close()
    stmpserver = STMPServer
    user = From
    password = password
    subject = '自动化测试报告'
    msgRoot = MIMEMultipart()
    text_msg = MIMEText(mailbody,'html','utf-8')
    msgRoot.attach(text_msg)
    file_msg = MIMEText(mailbody,'base64','utf-8')
    file_msg["Content-Type"] = 'application/octet-stream'
    basename = os.path.basename(file)
    file_msg["Content-Disposition"] = 'attachment; filename=''' + basename + ''
    msgRoot.attach(file_msg)
    msgRoot['Subject'] = Header(subject,'utf-8')
    msgRoot['From'] = From
    msgRoot['To'] = To
    smtp = smtplib.SMTP()
    smtp.connect(stmpserver)
    smtp.login(user, password)
    smtp.sendmail(msgRoot['From'], msgRoot['To'], msgRoot.as_string())
    smtp.quit()

if __name__ == '__main__':
    logprint = log.Log()
    logprint.logOutput()
    # test_suite = unittest.defaultTestLoader.discover('', pattern='maincase.py')
    test_suite = unittest.TestLoader().loadTestsFromTestCase(maincase.TestHmUi)
    result = BeautifulReport(test_suite)
    now = time.strftime("%Y%m%d%H%M%S")
    test_dir = '../TestReport/'
    report_dir = '../TestReport/'
    test_report = result.report(filename=now,description='', report_dir=report_dir, theme='theme_memories')
    report = NewReport(test_dir)
